package com.birboot.core;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.SplittableRandom;

public class ClientHandler  implements Runnable {
    private Socket socket;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    public void run(){
        try {
            //1.解析请求
            //1.1解析请求
            String line=readLine();
                System.out.print("请求行："+line);
                //请求相关信息
                String method ;//请求方式
                String uri;//抽象路径
                String protocol;//协议版本
                String[] a =line.split("\\s");
                method=a[0];
                uri=a[1];
                protocol=a[2];
            System.out.println("");
            System.out.println("method:"+method);
            System.out.println("uri:"+uri);
            System.out.println("protocol:"+protocol);
            //解析消息头
            Map<String,String> map = new HashMap<>();
            while (true) {
                line = readLine();
                if((line.isEmpty())){
                    break;
                }
                System.out.println("消息行：" + line);
                String[] s =line.split(":\\s");
                String tou =s[0];
                String tou1 = s[1];
                map.put(s[0],s[1]);
                    System.out.println(tou + "," + tou1);
            }
//                            map.put(s[0],s[1]);
//                System.out.println(map);
                
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String readLine() throws IOException {
        //
        InputStream is = socket.getInputStream();
        int d;
        char pre = 'a', cur = 'a';//pre代表上次读取的字符，cur代表这次读取的字符
        StringBuilder builder = new StringBuilder();//保存读取后的所有字符
        while ((d = is.read()) != -1) {
            cur = (char) d;//本次读取字符
            if (pre == 13 && cur == 10) {//判断是否为回车和换行
                break;
            }
            builder.append(cur);//将本次读取的字符拼接
            pre = cur;//把本次读取的字符给到pre
        }
        //将获取到的信息转换为字符串型，并去除首尾空白符
       return builder.toString().trim();
    }

}
